package com.cxd.app.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.cxd.app.constants.PublicConstants;
import com.cxd.app.entity.base.ProductRecordBase;
import com.cxd.app.entity.base.UserPointBase;
import com.cxd.app.entity.base.UserPointHistoryBase;
import com.cxd.app.mapper.read.RPointMapper;
import com.cxd.base.common.constants.UserPointHistoryConstants;
import com.cxd.base.common.exception.CxdException;
import com.cxd.base.page.PageUtil;
import com.cxd.base.page.tag.TagPage;
import com.cxd.base.util.BeanTools;
import com.cxd.base.util.IdGenerator;
import com.cxd.base.util.MapUtil;
import com.cxd.base.util.ParamUtil;
import com.cxd.base.util.date.DateUtil;
import com.cxd.message.exception.AppConstants;

/**
 * <一句话功能简述> <功能详细描述>
 * @author wtj
 * @date 2016年5月16日 上午11:13:18
 * @company CXD
 * @version [Copyright (c) 2016 V001]
 */
@Service("pointService")
public class PointService {
	
	@Resource
	public BeanTools bt;
	
	@Resource
	public RPointMapper rpiontMapper;
	
	@Resource
	public BeanService beanService;
	
	private static final Logger logger = Logger.getLogger(LoanService.class);
	
	/* 礼品列表 */
	public void giftRecommend(JSONObject json, String value)
			throws InstantiationException, IllegalAccessException {
		Map<String, Object> param = MapUtil.jsonToMap(value);
		Object pageSize = param.get("pageSize");
		Object currentPage = param.get("currentPage");
		if (pageSize == null || currentPage == null) {
			throw new CxdException("分页信息不能为空");
		}
		TagPage page = PageUtil.getTagPage(currentPage.toString(),pageSize.toString());
		param.put("page", page);
		
		List<Map<String,Object>> list = rpiontMapper.giftRecommendListPage(param);
		for(Map<String,Object> liMap:list){
			liMap.put("detailImgpath", AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+liMap.get("imgpath1"));
		}
		json.put("result", list.size() == 0 ? new String[] {} : list);
	}
	
	/* 礼品详情 */
	public void giftDetails(JSONObject json, String value)
			throws InstantiationException, IllegalAccessException {
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String productId = param.get("productId");
		String userId = param.get("userId");
		ParamUtil.notNullParam("产品ID:"+productId,"用户ID:"+userId);
		Map<String,Object> map = rpiontMapper.giftDetails(param);
		UserPointBase upBean = beanService.getUserPointByUserId(userId);
		if(upBean==null){
			map.put("userPoint", "0");
		}else{
			map.put("userPoint", beanService.getUserPointByUserId(userId).getPoint());
		}
		
		List<Object> picList= new ArrayList<Object>();
		Object i1 = map.get("imgpath1");
		Object i2 = map.get("imgpath2");
		Object i3 = map.get("imgpath3");
		Object i4 = map.get("imgpath4");
		if(i1!=null&& (!i1.equals(""))){
			picList.add(AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+i1);
		}
		if(i2!=null&& (!i2.equals(""))){
			picList.add(AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+i2);
		}
		if(i3!=null&& (!i3.equals(""))){
			picList.add(AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+i3);
		}
		if(i4!=null&& (!i4.equals(""))){
			picList.add(AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+i4);
		}
		
		map.put("detailImgpath", AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+map.get("detailImgpath"));
		map.put("imgpath1", AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+i1);
		map.put("imgpath2", AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+i2);
		map.put("imgpath3", AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+i3);
		map.put("imgpath4", AppConstants.PublicConstants.PIC_POINT_HTTP_PREFIX+i4);
		map.put("picList", picList);
		json.put("result", map==null ? new String[] {} : map);
	}
	
	/* 获取用户收货地址  */
	public void getUserAddress(JSONObject json, String value)
			throws InstantiationException, IllegalAccessException {
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		ParamUtil.notNullParam("用户ID:"+userId);
		Map<String,Object> map = rpiontMapper.getUserAddress(param);
		json.put("result", map==null ? new String[] {} : map);
	}
	
	/* 获取用户收货地址  */
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveUserAddress(JSONObject json, String value)
			throws InstantiationException, IllegalAccessException {
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		String username = param.get("username");
		String mobileNumber = param.get("mobileNumber");
		String address = param.get("address");
		String uphId = param.get("uphId");
		ParamUtil.notNullParam("用户ID:"+userId,"用户姓名:"+username,"联系方式:"+mobileNumber,"收货地址:"+address);
		int countNum = bt.queryForInt(String.format("select count(0) from address where user_id='%s'",userId));
		if(countNum == 0){
			param.put("id", IdGenerator.randomUUID());
			countNum = rpiontMapper.saveUserAddress(param);
		}else{
			countNum = rpiontMapper.updateUserAddress(param);
		}
		if(countNum==0){
			param.clear();
			param.put("status", "500");
			param.put("msg", "收货地址保存失败");
			json.put("result", param);
		}else{
			if(StringUtils.isNotBlank(uphId)){
				bt.update(String.format("update user_point_history set status ='%s' where id='%s'",UserPointHistoryConstants.status.delivery_to,uphId));
			}
		}
	}
	
	/* 获取用户抽奖记录  */
	public void getUserPointHistory(JSONObject json, String value)
			throws InstantiationException, IllegalAccessException {
		Map<String, Object> param = MapUtil.jsonToMap(value);
		Object pageSize = param.get("pageSize");
		Object currentPage = param.get("currentPage");
		Object userId = param.get("userId");
		ParamUtil.notNullParam("用户ID:"+userId);
		if (pageSize == null || currentPage == null) {
			throw new CxdException("分页信息不能为空");
		}
		TagPage page = PageUtil.getTagPage(currentPage.toString(),pageSize.toString());
		param.put("page", page);
		List<Map<String,Object>> list = rpiontMapper.getUserPointHistoryListPage(param);
		for(Map<String,Object> m:list){
			String operateType = m.get("operateType").toString();
			if(operateType.equals("add")){
				m.put("operateType", "invest");
			}
			m.put("investId", m.get("investId").toString().replace("投标编号：", ""));
		}
		json.put("result", list.size() == 0 ? new String[] {} : list);
	}
	
	
	/* 根据产品ID 获取投资信息  */
	public void getInvestByInvestId(JSONObject json, String value)
			throws InstantiationException, IllegalAccessException {
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String investId = param.get("investId");
		ParamUtil.notNullParam("投资ID:"+investId);
		Map<String,Object> map = rpiontMapper.getInvestByInvestId(param);
		map.put("rate",(int)(Float.parseFloat(map.get("rate").toString())*100));
		map.put("type",PublicConstants.loanTimeType.get(map.get("type").toString()));
		json.put("result", map==null ? new String[] {} : map);
	}
	
	/* 根据uphId获取产品信息   */
	public void getProductByUphId(JSONObject json, String value)
			throws InstantiationException, IllegalAccessException {
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String uphId = param.get("uphId");
		ParamUtil.notNullParam("uphId:"+uphId);
		Map<String,Object> map = rpiontMapper.getProductByUphId(param);
		Object expressCompany = map.get("expressCompany")==null?"无":map.get("expressCompany");
		Object expressNumber = map.get("expressNumber")==null?"无":map.get("expressNumber");
		map.put("expressCompany", expressCompany);
		map.put("expressNumber", expressNumber);
		json.put("result", map==null ? new String[] {} : map);
	}
	
	/* 根据uphId获取产品信息   */
	@SuppressWarnings("unused")
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveDHGift(JSONObject json, String value)
			throws InstantiationException, IllegalAccessException {
		
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String productId = param.get("productId");
		String productNum = param.get("productNum"); // 兑换商品数量
		String userId = param.get("userId");
		ParamUtil.notNullParam("商品ID:"+productId,"商品数量:"+productNum,"用户ID:"+userId);
		
		String sql = "select pro.position,pr.inventory,pro.integration from product pro LEFT JOIN product_record pr on pro.id=pr.product_id where pro.id='%s'";
		Map<String,Object> proMap = bt.queryMap(String.format(sql, productId));
		
		// 商品单价
		int integration = 0;
		// 库存商品数量
		int inventory = 0;
		if(proMap == null){
			throw new CxdException("商品不存在!");
		}else{
			// 商品单价
			integration = proMap.get("integration")==null?0:Integer.parseInt(proMap.get("integration").toString());
			// 库存商品数量
		    inventory = proMap.get("inventory")==null?0:Integer.parseInt(proMap.get("inventory").toString());
			if(Integer.parseInt(productNum)>inventory){
				throw new CxdException("库存不足!");
			}
		}
		
		sql = String.format("SELECT id,point,user_id,type from USER_POINT WHERE USER_ID = '%s'",userId);
		UserPointBase upBean = bt.queryBean(sql,UserPointBase.class);
		int xhPoint = integration*Integer.parseInt(productNum);
		if(upBean==null || xhPoint>upBean.getPoint()){
			throw new CxdException("积分不足!");
		}
		String uphId = IdGenerator.randomUUID();
		// 保存兑奖信息
		UserPointHistoryBase uphBase = new UserPointHistoryBase();
			uphBase.setId(IdGenerator.randomUUID());
			uphBase.setProductId(productId);
			uphBase.setTime(new Date());
			uphBase.setOperateType(UserPointHistoryConstants.operateType.minus);
			uphBase.setMode(UserPointHistoryConstants.mode.cost);
			uphBase.setPoint(-xhPoint);
			uphBase.setSurplusPoint(upBean.getPoint()-xhPoint);
			uphBase.setRemark(productId);
			uphBase.setStatus(UserPointHistoryConstants.status.delivery_to);
			uphBase.setType(UserPointHistoryConstants.type.consume);
			uphBase.setTypeInfo("APP-积分兑换商品");
			uphBase.setUserId(userId);
			uphBase.setExchangeNumber(productNum);
		bt.add(uphBase);
		
		// 修改用户积分
		upBean.setPoint(upBean.getPoint()-xhPoint);
		upBean.setLastUpdateTime(new Date());
		bt.modify(upBean);
		
		bt.update(String.format("update product_record set INVENTORY=INVENTORY-%s,SALE_NUMBER=SALE_NUMBER+%s where PRODUCT_ID='%s'",productNum,productNum,productId));
		ProductRecordBase prb = bt.queryBean("product_record","PRODUCT_ID",productId,ProductRecordBase.class);
		if(prb.getInventory()<0){
			throw new CxdException("库存不足！");
		}
		param.clear();
		param.put("uphId", uphId);
		json.put("result", param);
	}
	
	
	/* 保存抽奖操作   */
	@SuppressWarnings("unused")
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveLuckDraw(JSONObject json, String userId)
			throws InstantiationException, IllegalAccessException {
		Map<String,Object> prizeMap = new HashMap<String,Object>();
//		Map<String, String> param = MapUtil.jsonToMapString(value);
//		String user_id = param.get("user_id");
		ParamUtil.notNullParam("用户ID:"+userId);
		UserPointBase upBean = getUserPoint(userId);
		if(UserPointHistoryConstants.prizeOne > upBean.getPoint()){
			throw new CxdException("用户积分不足");
		}
		List<Map<String,Object>> liMap = rpiontMapper.queryPrizeInfo();
		// if(true || liMap==null || liMap.size()==0){
		if(liMap==null || liMap.size()==0){
			json.put("status", "200");
			prizeMap.put("type", 3);
			prizeMap.put("position", 0);
			json.put("prizeMap", prizeMap);
		}else{
			for(Map<String,Object> lm:liMap){
				int rate = Integer.parseInt(lm.get("rate").toString());
				Random random = new Random();
				int prizeInt = random.nextInt(rate);
				if(liMap.get(liMap.size()-1).equals(lm)){
					prizeInt = 0;
				}
				if(prizeInt == 0){
					Date nowDate = new Date();
					prizeMap = lm;
					
					int integration = Integer.parseInt(prizeMap.get("integration").toString());
					// 产品ID
					String productId = prizeMap.get("productId").toString();
					String type = prizeMap.get("type").toString();
					
					// 更改用户积分
					upBean.setPoint(upBean.getPoint()-UserPointHistoryConstants.prizeOne);
					upBean.setLastUpdateTime(nowDate);
					bt.modify(upBean);
					
					String uphId = IdGenerator.randomUUID();
					
					String status = "";
					if(type.equals(UserPointHistoryConstants.prizeType.zero)){
						status = UserPointHistoryConstants.status.delivery_to;
					}else if(type.equals(UserPointHistoryConstants.prizeType.one)){
						status = UserPointHistoryConstants.status.verify;
					}else if(type.equals(UserPointHistoryConstants.prizeType.two)){
						status = UserPointHistoryConstants.status.delivery_complete;
					}
					// 保存抽奖
					UserPointHistoryBase uphBase = new UserPointHistoryBase();
						uphBase.setId(uphId);
						uphBase.setProductId(productId);
						uphBase.setTime(nowDate);
						uphBase.setOperateType(UserPointHistoryConstants.operateType.minus);
						uphBase.setMode(UserPointHistoryConstants.mode.prize);
						uphBase.setPoint(-UserPointHistoryConstants.prizeOne);
						uphBase.setSurplusPoint(upBean.getPoint());
						uphBase.setRemark(productId);
						uphBase.setStatus(status);
						uphBase.setType(UserPointHistoryConstants.type.consume);
						uphBase.setTypeInfo("APP-积分抽奖");
						uphBase.setUserId(userId);
						uphBase.setExchangeNumber("1");
					bt.add(uphBase);
	
					// 减少库存
					bt.update(String.format("update product_record set INVENTORY=INVENTORY-1,SALE_NUMBER=SALE_NUMBER+1 where PRODUCT_ID='%s'",productId));
					ProductRecordBase prb = bt.queryBean("product_record","PRODUCT_ID",productId,ProductRecordBase.class);
					if(prb.getInventory()<0){
						throw new CxdException("库存不足！");
					}
					
					// 如果抽取到的是积分
					if(prizeMap.get("type").equals("2")){
						upBean.setPoint(uphBase.getSurplusPoint()+integration);
						upBean.setLastUpdateTime(nowDate);
						bt.modify(upBean);
						
						// 保存兑奖信息
						UserPointHistoryBase uphBase1 = new UserPointHistoryBase();
						uphBase1.setId(IdGenerator.randomUUID());
						uphBase1.setProductId(productId);
						uphBase1.setTime(DateUtil.addSecond(nowDate, 1));
						uphBase1.setOperateType(UserPointHistoryConstants.operateType.add);
						uphBase1.setMode(UserPointHistoryConstants.mode.prize);
						uphBase1.setPoint(integration);
						uphBase1.setSurplusPoint(upBean.getPoint());
						uphBase1.setRemark(productId);
						uphBase1.setStatus(UserPointHistoryConstants.status.delivery_complete);
						uphBase1.setType(UserPointHistoryConstants.type.cost);
						uphBase1.setTypeInfo("APP-积分抽奖抽取积分-抽奖ID"+uphId);
						uphBase1.setUserId(userId);
						uphBase1.setExchangeNumber("1");
						bt.add(uphBase1);
					}
					
					prizeMap.put("uphId", uphId);
					prizeMap.put("position", Integer.parseInt(prizeMap.get("position").toString())/10);
					json.put("prizeMap", prizeMap);
					break;
				}
			}
		}
		
		if(prizeMap==null || prizeMap.get("type")==null){
			json.put("status", "200");
			prizeMap.put("type", 3);
			prizeMap.put("position", 0);
			json.put("prizeMap", prizeMap);
		}
	}
	
	// 获取用户积分
	public UserPointBase getUserPoint(String userId){
		return bt.queryBean(String.format("SELECT id,point,user_id,type from USER_POINT WHERE USER_ID = '%s'",userId),UserPointBase.class);
	}
	public static void main(String[] arg){
		Map<String,Object> m1 = new HashMap<String,Object>();
		m1.put("rate","6");
		Map<String,Object> m2 = new HashMap<String,Object>();
		m2.put("rate","5");
		Map<String,Object> m3 = new HashMap<String,Object>();
		m3.put("rate","4");
		Map<String,Object> m4 = new HashMap<String,Object>();
		m4.put("rate","3");
		Map<String,Object> m5 = new HashMap<String,Object>();
		m5.put("rate","2");
		Map<String,Object> m6 = new HashMap<String,Object>();
		m6.put("rate","1");
		
		List<Map<String,Object>> liMap = new ArrayList<Map<String,Object>>();
		liMap.add(m1);
		liMap.add(m2);
		liMap.add(m3);
		liMap.add(m4);
		liMap.add(m5);
		liMap.add(m6);
		
		Map<String,Object> prizeMap = new HashMap<String,Object>();
		for(Map<String,Object> lm:liMap){
			int rate = Integer.parseInt(lm.get("rate").toString());
			Random random = new Random();
			int prizeInt = random.nextInt(rate);
			if(prizeInt == 0){
				prizeMap = lm;
				System.out.println(lm.get("rate").toString());
				break;
			}
		}
	}
}
